<?php


namespace App\Service\VendorClient\ShopywymApi;


use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;

class ShopywymApiClient extends BaseService
{
    protected $clientConfig;

    /**
     * 初始参数
     * @param array $apiBody
     */
    public function __construct($apiBody = [])
    {
        $this->clientConfig = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];

        //支付流水号
        $pay_sn    = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //支付时间
        $pay_time   = date('Y-m-d H:i:s', time());
        //支付流水号
        $order_sn       = $orderInfo['supplier_dsn'];

        //判断支付方式是否存在
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        $enterpriseNum = $order['enterpriseNum']??$apply_extends['enterpriseNum']??'';
        //获取电商平台映射配置
        $channel_value = ServiceConfig::instance()->getConfigByEventsValue('shopywym', ServiceConfig::TYPE_CHANNEL, $enterpriseNum);
        if (empty($channel_value)) {
            return Normal::returnCode(Normal::FAIL, "支付电商平台编码：【{$enterpriseNum}】未映射，请联系管理员处理");
        }
        //获取支付方式配置
        $PayCompanyCode =$order['payCommanyCode']??$apply_extends['payCommanyCode']??'';
        $pay_value = ServiceConfig::instance()->getConfigByEventsValue('shopywym', ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "义乌义贸当前不支持支付方式：{$PayCompanyCode}");
        }

        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        $way_tax_fee        = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            
            //单价含税单价需要把第三位往上收取，不能单独不含税价和税金分开计算，需要做减法
            $singlePrice        = bcdiv((string)$price, (string)$spec_num,3);
            $singlePrice        = bcmul((string)$singlePrice,'100',1);
            $singlePrice        = bcdiv((string)ceil($singlePrice),'100',2);
            
            //不含税价格
            $notTaxGoodsSinglePrice = bcdiv((string)$singlePrice, $tax_rate,3);
            $notTaxGoodsSinglePrice = bcmul((string)$notTaxGoodsSinglePrice,(string)'100',1);
            $notTaxGoodsSinglePrice = bcdiv((string)ceil($notTaxGoodsSinglePrice),'100',2);
            
            $buyNum             = $spec_num * $quantity;
            $goodsTotalPrice    = bcmul((string)$notTaxGoodsSinglePrice,(string)$buyNum,2);
            
            //商品关税当前币种最小单位（分）
            $goodsCustomsTax    = bcsub((string)$singlePrice,(string)$notTaxGoodsSinglePrice,2);
            $taxAll             = bcmul($goodsCustomsTax,(string)$buyNum,2);
            
            $goodsInfo = [
                "commodityCode"           => $item['supplier_skucode'],
                "commodityName"           => $item['goods_name'],
                "qty"                     => $buyNum,
                "price"                   => (string)$notTaxGoodsSinglePrice,
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney    = bcadd((string)$goodsTotalMoney,$goodsTotalPrice,2);
            $way_tax_fee        = bcadd((string)$way_tax_fee,$taxAll,2);
        }

        //订单总价（商品保税价格 + 运费）
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,2);
        $totalMoney             = bcadd($totalMoney, (string)$way_tax_fee,2);
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,2);
        //创建订单数据
        $data=[
            'orderCode'                  => $order_sn,//订单号
            'platformCode'               => $channel_value, 
            'consignee'                  => $orderInfo['receive_name'],
            'mobile'                     => $orderInfo['recveive_phone'],
            'province'                   => $orderInfo['province'],
            'city'                       => $orderInfo['city'],
            'district'                   => $orderInfo['district'],
            'address'                    => $orderInfo['receive_address'],
            'payCompany'                 => $pay_value,
            'payNumber'                  => $pay_sn,
            'payDate'                    => $pay_time,
            'peopleId'                   => $orderInfo['buyer_idcard'],
            'realName'                   => $orderInfo['buyer_realname'],
            'orderDate'                  => date('Y-m-d H:i:s', $orderInfo['cd']),
            'orderGoodsAmount'           => $goodsTotalMoney,
            'orderTaxAmount'             => $way_tax_fee,
            'feeAmount'                  => $deliver_money,
            'couponAmount'               => $discount_money,
            'paymentAmount'              => $real_total_money,
            'orderDetail'                => $goodsList,
        ];
        
        $requestParam = [
            'method'    => 'OrderCreate',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * 获取发货物流信息
     */
    public function queryOrderExpress( $param = [] )
    {
        $data = [
            "orderNo"  => $param['supplier_dsn'],
        ];
        $requestParam = [
            'method'    => 'queryExpress',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($params = [])
    {
        $method = $params['method'];
        $header = [
            'Content-Type: application/x-www-form-urlencoded',
            'Expect:'
        ];
        $data  = [
            'businessId'     => $this->clientConfig['businessId'],
            'timestamp'      => time(),
            'method'         => $this->clientConfig[$method],
            'data'           => json_encode($params['data'],JSON_UNESCAPED_UNICODE)
        ];
        $data['sign']   = $this->getSign($data);
        $url            = $this->clientConfig['baseurl'];
        $parameter = [
            [
                'tag'      => 'Shopywym_' . $method,
                'uid'      => IdService::instance()->getOtherID(),
                'url'      => $url,
                'data'     => $data,
                'method'   => 'post',
                'format'   => 'x-www-form-urlencoded',
                'header'   => $header,
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask  = current($resTask);
        $httpCode = $resTask['response']['httpCode'];
        $resHttp = @json_decode($resTask['response']['result'], true);
        $errorMsg = $resHttp['message'] ??  '请求失败';
        if ($httpCode==Normal::SUC && $resHttp['success'] == true) {
            return Normal::returnCode(Normal::SUC, "操作成功", $resHttp);
        }
        return Normal::returnCode(Normal::FAIL, $errorMsg);
    }

    /**
     * 获取sign参数
     */
    private function getSign( $param = [] )
    {
        ksort($param);
        $arr = [];
        foreach ($param as $k => $v) {
            $arr[] = "{$k}{$v}";
        }
        $str = implode("", $arr);
        $str = $this->clientConfig['token'].$str.$this->clientConfig['token'];
        return md5($str);
    }


}
